﻿using Dora.Tools.Enums.Order;
using Dora.Tools.Insurance.AM.Dto;
using Dora.Tools.Insurance.AYB;
using Dora.Tools.Insurance.AYB.Dto;
using Dora.Tools.Insurance.JT.Dto;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Dora.Tools.Insurance
{
    /// <summary>
    /// 订单调用保险接口管理类
    /// </summary>
    public class OrderInsuranceManager
    {
        /// <summary>
        /// 投保
        /// </summary>
        /// <param name="result">保险账号信息</param>
        /// <param name="requestDto">保险投保数据</param>
        /// <param name="bizLicenseKey">旅行社许可证</param>
        /// <param name="orgName">组织机构名称</param>
        /// <param name="creditCode">大社统一社会信用代码</param>
        /// <returns></returns>
        public static OrderInsuranceResultDto Apply(InsuranceOrgSupplierInfo result, RequestInsuranceDto requestDto, string bizLicenseKey, string orgName, string creditCode)
        {
            //4.调用保险供应商接口投保 返回保单号
            bool status = false;
            string tradingCode = Guid.NewGuid().ToString().Replace("-", "");//交易号 调用保险接口时传递
            string policyCode = string.Empty;//保单号 接口返回
            string insuranceOrderUrl = string.Empty;//保单下载地址
            string error = string.Empty;
            switch (result.SupplierId)
            {
                case 1: // 安游保
                    string appid = result.Ext1;
                    string sign = result.Ext2;
                    ApplyInfoData AYBdata = AssemblyApplyDataHelper.AssemblyAYBData(requestDto, tradingCode, orgName, creditCode);
                    ApplyResponseDto aybApply = AYBInsuranceHelper.Apply(appid, sign, AYBdata);
                    if (aybApply != null)
                    {
                        if (aybApply.code == "000")
                        {
                            status = true;
                            policyCode = aybApply.data.policy_no;
                            insuranceOrderUrl = aybApply.data.pdf_url;
                        }
                        else
                        {
                            error = aybApply.msg;
                        }
                    };
                    break;
                case 2: // 江泰
                    string channelComCode = result.Ext1;// 江泰渠道机构代码
                    string travelAgencyCode = result.Ext2; // 江泰旅行社代码
                    string channelBusinessCode = result.Ext3; // 江泰渠道业务代码
                    string md5Key = result.Ext4; //江泰Md5key
                    string travelAgencyLicenseCode = bizLicenseKey;////获取大社旅行许可证号
                    string invoiceTitle = orgName;//发票抬头 大社名称
                    string taxpayerIdentificationNumber = creditCode;//纳税人识别码 大社统一社会信用代码
                    InsureOrderRequestDto JTdata = AssemblyApplyDataHelper.AssemblyJTData(requestDto, "", channelComCode, travelAgencyCode, travelAgencyLicenseCode, channelBusinessCode, tradingCode,
                            invoiceTitle, taxpayerIdentificationNumber);
                    ChinaTourinsResponseDto jtApply = JTInsuranceHelper.InsureOutOrder(md5Key, JTdata);
                    if (jtApply != null)
                    {
                        if (jtApply.responseCode == "000001")
                        {
                            status = true;
                            policyCode = jtApply.policyNo;
                            insuranceOrderUrl = JTInsuranceHelper.GetJTInsurePdf_Url(jtApply.channelTradeSerialNo, travelAgencyCode);
                        }
                        else
                        {
                            error = jtApply.responseMessage;
                        }
                    };
                    break;
                case 3: // 安馒
                    string userName = result.Ext1;
                    string pwd = result.Ext2;
                    AMApplyRequestDto AMdata = AssemblyApplyDataHelper.AssemblyAMData(requestDto, tradingCode, userName, orgName, creditCode);
                    AMApplyResponseDto amApply = AMInsuranceHelper.Apply(pwd, AMdata);
                    if (amApply != null)
                    {
                        if (amApply.Code == "0000")
                        {
                            status = true;
                            policyCode = amApply.SegmentList[0].PolicyCode;
                            insuranceOrderUrl = amApply.SegmentList[0].EPolicyUrl;
                        }
                        else
                        {
                            error = amApply.Message;
                        }
                    };
                    break;
            }

            OrderInsuranceResultDto resultDto = new OrderInsuranceResultDto()
            {
                TradingCode = tradingCode,
                PolicyCode = policyCode,
                InsuranceOrderUrl = insuranceOrderUrl,
                Msg = error,
                Status = status ? (short)OrderInsuranceStatus.ApplySucess : (short)OrderInsuranceStatus.ApplyFail
            };

            return resultDto;
        }

        /// <summary>
        /// 撤保
        /// </summary>
        /// <param name="result">保险账号信息</param>
        /// <param name="policyCode">保单号</param>
        /// <param name="tradingCode">流水号</param>
        /// <param name="bizLicenseKey">旅行社许可证</param>
        /// <returns></returns>
        public static CancelResult Cancel(InsuranceOrgSupplierInfo result, string policyCode, string tradingCode, string bizLicenseKey)
        {
            bool status = false;
            string name = string.Empty;
            string errMsg = string.Empty;
            switch (result.SupplierId)
            {
                case 1: // 安游保
                    #region 安游宝退保
                    string appid = result.Ext1;
                    string sign = result.Ext2;
                    name = "安游保";
                    CancelDataDto cancelAYBDto = new CancelDataDto { policy_no = policyCode, biz_order_sn = tradingCode };
                    CancelResponseDto cancelAYB = AYBInsuranceHelper.Cancel(appid, sign, cancelAYBDto);
                    if (cancelAYB != null)
                    {
                        if (cancelAYB.code == "000") { status = true; }
                        else { errMsg = cancelAYB.msg; status = false; }
                    };
                    #endregion
                    break;
                case 2: // 江泰
                    #region 江泰退保
                    string channelComCode = result.Ext1;// 江泰渠道机构代码
                    string travelAgencyCode = result.Ext2; // 江泰旅行社代码
                    string channelBusinessCode = result.Ext3; // 江泰渠道业务代码
                    string md5Key = result.Ext4; //江泰Md5key
                    name = "江泰";
                    ChinaTourinsRequest tourinsRequest = new ChinaTourinsRequest()
                    {
                        channel = "",
                        channelComCode = channelComCode,
                        travelAgencyCode = travelAgencyCode,
                        travelAgencyLicenseCode = bizLicenseKey,
                        channelTradeCode = "CHD",
                        channelBusinessCode = channelBusinessCode,
                        channelTradeDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),//渠道交易日期
                        channelTradeSerialNo = tradingCode,//交易流水号
                        channelOperateCode = "渠道操作员代码"
                    };
                    InsureOrderRequestDto cacelJTDto = new InsureOrderRequestDto() { ChinaTourinsRequest = tourinsRequest };
                    CancelChinaTourinsResponseDto cancelChina = JTInsuranceHelper.CancelInsureOutOrder(md5Key, cacelJTDto);
                    if (cancelChina.responseCode == "000001") { status = true; }
                    else { errMsg = cancelChina.responseMessage; status = false; }
                    #endregion;
                    break;
                case 3: // 安馒
                    #region 安馒退保
                    string userName = result.Ext1;
                    string pwd = result.Ext2;
                    name = "安馒";
                    AMCancelRequestDto cancelAMDto = new AMCancelRequestDto()
                    {
                        TradeCode = tradingCode,
                        UserName = userName,
                        SegmentList = new List<PolicyRequestDto>() {
                                    new PolicyRequestDto()
                                    {
                                        PolicyCode=policyCode
                                    }
                            }
                    };
                    AMCancelResponseDto cancelAM = AMInsuranceHelper.Cancel(pwd, cancelAMDto);
                    if (cancelAM != null)
                    {
                        if (cancelAM.Code == "0000") { status = true; }
                        else { errMsg = cancelAM.Message; status = false; }
                    };
                    #endregion;
                    break;
            }
            CancelResult cancel = new CancelResult()
            {
                Status = status,
                Msg = errMsg
            };
            return cancel;
        }

        /// <summary>
        /// 查询余额
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        public static decimal QueryInsuraceBalance(InsuranceOrgSupplierInfo result)
        {
            decimal balance = 0;
            switch (result.SupplierId)
            {
                case 1: // 安游保
                    string appid = result.Ext1;
                    string sign = result.Ext2;
                    try
                    {
                        AvailableBalanceResponeDto balanceResponeDto = AYBInsuranceHelper.GetAvailableBalance(appid, sign);
                        if (balanceResponeDto != null)
                        {
                            balance = balanceResponeDto.data.available_balance;
                        }
                    }
                    catch (Exception ex)
                    {
                        balance = 0;
                    }
                    break;
                case 2: // 江泰
                    string channelComCode = result.Ext1;// 江泰渠道机构代码
                    string travelAgencyCode = result.Ext2; // 江泰旅行社代码
                    string channelBusinessCode = result.Ext3; // 江泰渠道业务代码
                    string md5Key = result.Ext4; //江泰Md5key
                    try
                    {
                        QueryBlanceRequest query = new QueryBlanceRequest()
                        {
                            travelAgencyCode = travelAgencyCode,
                            enterpriseId = "0"
                        };
                        QueryBlanceRequestDto getBalance = new QueryBlanceRequestDto()
                        {
                            QueryBlanceRequest = query
                        };
                        QueryBlanceResponseDto responseDto = JTInsuranceHelper.QueryBlanceInsureOutOrder(md5Key, getBalance);
                        if (responseDto.Status == 200)
                        {
                            balance = responseDto.Data.blance;
                        }
                    }
                    catch (Exception ex)
                    {
                        balance = 0;
                    }
                    break;
                case 3: // 安馒
                    string userName = result.Ext1;
                    string pwd = result.Ext2;
                    try
                    {
                        AMGetBalanceRequestDto requestDto = new AMGetBalanceRequestDto()
                        {
                            TradeCode = "123456",
                            UserName = userName
                        };
                        AMGetBalanceResponseDto aMGetBalance = AMInsuranceHelper.GetBalance(pwd, requestDto);
                        if (aMGetBalance != null)
                        {
                            balance = aMGetBalance.Balance;
                        }
                    }
                    catch (Exception ex)
                    {
                        balance = 0;
                    }
                    break;
            }
            return balance;
        }
    }

    /// <summary>
    /// 返回信息
    /// </summary>
    public class CancelResult
    {
        /// <summary>
        /// 状态
        /// </summary>
        public bool Status { get; set; }

        /// <summary>
        /// Msg
        /// </summary>
        public string Msg { get; set; }
    }

    /// <summary>
    /// 保险投保返回信息
    /// </summary>
    public class OrderInsuranceResultDto
    {
        public int Id { get; set; }

        /// <summary>
        /// 交易号 调用保险接口时传递
        /// </summary>
        public string TradingCode { get; set; }

        /// <summary>
        /// 保单号 接口返回
        /// </summary>
        public string PolicyCode { get; set; }

        /// <summary>
        /// 保单下载地址
        /// </summary>
        public string InsuranceOrderUrl { get; set; }

        /// <summary>
        /// 状态 枚举：0-未发起投保 1-投保成功 2-退保成功 3-投保失败 4-退保失败
        /// </summary>
        public int Status { get; set; }

        public string Msg { get; set; }
    }

    /// <summary>
    /// 保险账号信息
    /// </summary>
    public class InsuranceOrgSupplierInfo
    {
        /// <summary>
        /// 组织机构Id;organization表主键
        /// </summary>
        public int OrgId { get; set; }

        /// <summary>
        /// 保险供应商Id;insurance_supplier表主键
        /// </summary>
        public int SupplierId { get; set; }

        /// <summary>
        /// 扩展字段1;江泰渠道机构代码/安游保的app_id/安馒的用户名
        /// </summary>
        public string Ext1 { get; set; }

        /// <summary>
        /// 扩展字段2;江泰旅行社代码/sign签名/安馒的密码
        /// </summary>
        public string Ext2 { get; set; }

        /// <summary>
        /// 扩展字段3;江泰渠道业务代码
        /// </summary>
        public string Ext3 { get; set; }

        /// <summary>
        /// 扩展字段4;江泰Md5key
        /// </summary>
        public string Ext4 { get; set; }

        /// <summary>
        /// 扩展字段5
        /// </summary>
        public string Ext5 { get; set; }

        /// <summary>
        /// 扩展字段6
        /// </summary>
        public string Ext6 { get; set; }

        /// <summary>
        /// 扩展字段7
        /// </summary>
        public string Ext7 { get; set; }

        /// <summary>
        /// 扩展字段8
        /// </summary>
        public string Ext8 { get; set; }
    }
}
